<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="keywords" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="queryEmp">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
    <el-table :data="employees" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" label="序号" width="60">
      </el-table-column>
      <el-table-column prop="username" label="姓名" width="100" sortable>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="200" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" >
        <template scope="scope">
          <span style="color: green" v-if="scope.row.state =='1'">启用</span>
          <span style="color: red" v-if="scope.row.state =='0'">禁用</span>
        </template>
      </el-table-column>
     <!-- <el-table-column prop="manager.username" label="经理" width="100" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="100" sortable>
      </el-table-column>-->
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :total="totals"
                     :current-page="currentPage"
                     style="float:right;">
      </el-pagination>
		</el-col>

    <!-- 添加或修改的对话框
    el-dialog - elementUi提供的对话框 = 模态框
      :title="title" - 动态改变标题
      :visible.sync="saveFormVisible"  - 模态框的显示状态
      :close-on-click-modal="false" - 关闭模态框只能通过模态框的x关闭，点击空白处不能关闭模态框
    el-form - 表单
      :model="saveForm" - 绑定表单对象
      label-width="80px" - 标签宽度
      :rules="saveFormRules" - 验证规则
      ref="saveForm" - 为当前模态框取名
      prop="name" - 如果当前字段要验证，就必须写，出现*
      auto-complete="off" - 不自动提示
-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="电话" prop="phone">
          <el-input v-model="saveForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="username">
          <el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="部门经理">
          &lt;!&ndash;
            el-select - 下拉框
              v-model="saveForm.manager" - 回显数据
              placeholder="请选择" - 提示语
              clearable - 可清理
              el-option - 每一个选项
              v-for="item in managers" - 遍历
              :label="item.username" - 回显哪一个值：item对象的username属性
              :value="item" - 点击保存你要传递到后端的数据
            回显机制：
              v-model="saveForm.manager"  与 v-for中的对应
              :label="item.username" - 回显哪一个值：item对象的username属性
              value-key	作为 value 唯一标识的键名，绑定值为对象类型时必填
              value-key="id" - 因为我们绑定的是一个对象saveForm.manager，
                对象里面有多个值： id: 324, username: "东邪"
              使用id作为回显的唯一标识
          &ndash;&gt;
          <el-select v-model="saveForm.manager" value-key="id" placeholder="请选择" clearable>
            <el-option v-for="item in managers"
                       :label="item.username"
                       :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}
            </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-input v-model="saveForm.parent_id" auto-complete="off"></el-input>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交			</el-button>
      </div>
    </el-dialog>


	</section>
</template>

<script>

	export default {
		data() {
			return {
				filters: {
					username: ''
				},
        //分页查询 - 显示分页列表数据
        employees: [],
        //分页查询 - 总数量 - 计算分页栏
        totals: 0,
        //分页查询 - 当前页 - 计算分页栏
        pageSize: 5,
        //分页查询 - 每页显示的条数 - 分页栏显示页数
        currentPage: 1,
				listLoading: false,
				sels: [],//列表选中列
        keywords: null,
        //添加或修改数据
        saveFormVisible: false,	//添加或修改界面是否显示
        saveLoading: false,		//加载框
        title: '',
        //标题
        managers: [],
        saveFormRules: {		//验证规则
          phone: [
            { required: true, message: '请输入员工电话', trigger: 'blur' }
          ],
          username: [
            { required: true, message: '请输入员工名称', trigger: 'blur' }
          ]
        },
        //编辑界面数据
        saveForm: {
          id: null,
          phone: '',
          username: '',
          state: 1,
          manager_id: null,
          parent_id: null
        }
			}
		},
		methods: {
		  queryEmp(){
		    this.currentPage=1;
		    this.getEmployees();
      },
      getManagers(){
        this.$http.get("/emp").then(res => {
          this.managers = res.data;
        })
      },
			//性别显示转换
      formatState: function (row, column) {
				return row.state == 1 ? '启用' : row.state == 0 ? '禁用' : '未知';
			},
			handleCurrentChange(val) {
        //当前页
        this.currentPage = val;
        this.getEmployees();
			},
			//获取用户列表
			getEmployees() {
				let para = {
					currentPage: this.currentPage,
          keywords: this.keywords
				};
				this.listLoading = true;
				//NProgress.start();
				this.$http.post("/emp",para)
            .then(res=>{
              this.totals = res.data.totals;
              this.employees = res.data.data;
              this.listLoading = false;
            })
            .catch(res=>{
              this.$message.error('系统繁忙，请稍后重试!!!');
            })
			},
      //删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.delete("/emp/" + row.id).then(res => {
            this.listLoading = false;
            if(res.data.success){
              //计算总页数
              let totalPage = this.totals%this.pageSize==0?this.totals/this.pageSize
                  :Math.ceil(this.totals/this.pageSize);
              if(this.currentPage > 1 && this.currentPage==totalPage && (this.totals-1)%this.pageSize==0){
                this.currentPage = this.currentPage - 1;
              }
              this.getEmployees();
            }else{
              this.$message.error("删除失败【500】");
            }
          }).catch(res => {
            this.$message.error("系统错误【400,404】");
          })
        }).catch(() => {
          //确认框点击取消之后走这里
        });
      },
      //点击修改按钮弹出对话框
      handleEdit: function (index, row) {
        this.title = "编辑";
        //克隆数据：防止对象引用修改显示的数据
        this.saveForm = Object.assign({}, row);
        this.getManagers();
        this.saveFormVisible = true;
      },

//点击添加按钮弹出对话框
      handleAdd: function () {
        this.title = "添加";
        this.saveForm = {
          id: null,
          phone: '',
          username: '',
          state: 1,
          manager_id: null,
          parent_id: null
        };
        this.saveFormVisible = true;//显示对话框
      },

//点击模态框提交数据
      saveSubmit: function () {
        this.$refs.saveForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              let paras = Object.assign({}, this.saveForm);
              this.$http.put("/emp",paras).then(res => {
                this.saveFormVisible = false;
                this.saveLoading = false;
                if(res.data.success){
                  this.$message.success("操作成功");
                  this.getEmployees();
                }else{
                  this.$message.error("操作失败【500】");
                }
              }).catch(res => {
                this.$message.error("系统错误【400,404】");
              })
            });
          }
        });
      },
      //改变批量删除的id集合触发事件
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					this.$http.patch("/emp",ids).then(res=>{
            this.listLoading = false;
            if(res.data.success){
              this.currentPage = 1;
              this.getEmployees();
            }else{
              this.$message.error("批量删除失败【500】");
            }
          }).catch(res=>{
            this.$message.error("系统错误【400,404】");
          })
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getEmployees();
		}
	}

</script>

<style scoped>

</style>